package com.qfedu.yanglao20.common.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yujie
 * @data 2023/4/18 18:26
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    // 针对指定的注解设置切点
    @Pointcut("@annotation(com.qfedu.yanglao20.common.annotation.LogInfo)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {

        // 获取方法名，获取参数
        // 获取方法名
        String name = joinPoint.getSignature().getName();
        // 获取方法的参数
        Object[] args = joinPoint.getArgs();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取方法的请求路径
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes()).getRequest();
        // 请求路径
        String url = request.getRequestURI().toString();

        // 获取方法的参数信息
        Parameter[] parameters = method.getParameters();

        Map<String, Object> map = new HashMap<>();

        if (args != null) {
            for (int i = 0; i < parameters.length; i++) {
                map.put(parameters[i].getName(), args[i]);
            }
        }

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String paramJson = objectMapper.writeValueAsString(map);
            log.info("method:{}, params:{}, url:{}", name, paramJson, url);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


//        log.info("方法:{}, 参数:{}, 参数信息:{}", name, Arrays.toString(args), Arrays.toString(parameters));
    }
}
